local filename = "httprequest.lua"

local skynet = require "skynet"
local filelog =require "filelog"
local timetool = require "timetool"

require "pubenum"

local service = nil
local CMD = {
	service = nil
}

--请求次数
local request_cnt = 0
--请求失败次数
local requesterr_cnt = 0
--上次请求时间
local last_reqtime = 0
 --请求超时时间，5s
local request_outtime = 5
--最大同时请求次数
local max_syncreq_cnt = 2

--
--发送http请求
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end

    --请求中，直接返回
    local curtime = timetool.get_time()
    if requesterr_cnt > 0 then
        if (curtime - last_reqtime) < requesterr_cnt then
            return { retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "系统繁忙，请稍后重试"}
        end
    end
    if request_cnt >= max_syncreq_cnt then
        if (curtime - last_reqtime) < request_outtime then
            return { retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "网络繁忙，请稍后重试"}
        end
        request_cnt = 1
    else
        request_cnt = request_cnt + 1
    end

    --验证参数合法性
    local request_url = tostring(msgbody.request_url) or ""
    if request_url == "" then
        request_cnt = request_cnt - 1
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "无效的请求"}
    end

    --发送http请求
    last_reqtime = curtime
    local result = skynet.call(".mainnode", "lua", "cmd", "send_http_request", rid, request_url)
    request_cnt = request_cnt - 1
    if result then
        requesterr_cnt = 0
        return {response_url = result, callback_addr = msgbody.callback_addr, request_type = msgbody.request_type}
    elseif result == false then
        if requesterr_cnt == 0 then
            requesterr_cnt = 1
        else
            requesterr_cnt = requesterr_cnt * 2
        end
    end
    
	return { retcode = EErrCode.ERR_NET_EXCEPTION, retstr = "请求失败" }
end

return CMD